<template>
  <section class="strategy-pool">
    <div class="title">{{ title }}</div>
    <empty-pool v-if="isNoData" :desc="emptyText"></empty-pool>
    <div :class="{ 'box-center': showLoading }" v-else>
      <atom-loading v-if="showLoading" />
      <div class="selected-pool" v-else>
        <!-- 日期 -->
        <atom-sticky v-if="showDatePick">
          <atom-calendar-tab
            v-model="selectedDate"
            @input="onDateChange"
            :max-date="maxDate"
            :weekFormatter="weekFormatter"
            :filter="filterDate"
            @click-calendar="show"
          >
          </atom-calendar-tab>
        </atom-sticky>
        <atom-calendar
          v-model="showCalendar"
          :max-date="maxDate"
          :default-date="selectedDate"
          :effect-date-rule="filterCalendar"
          @confirm="confirm"
        >
        </atom-calendar>
        <!-- 工具栏 -->
        <atom-sticky offset-top="16.53vw">
          <div class="tool">
            <div></div>
            <div class="toggle" v-if="stockList.length">
              <span class="btn" @click="currentMode = 0" :class="{ active: currentMode === 0 }"
                >列表</span
              >
              <div class="split"></div>
              <span class="btn" @click="currentMode = 1" :class="{ active: currentMode === 1 }"
                >卡片</span
              >
            </div>
          </div>
        </atom-sticky>
        <!-- 列表 -->
        <template v-if="currentMode === 0">
          <etf-list :stockList="stockList" offsetTop="29.86vw"></etf-list>
        </template>
        <!-- 卡片 -->
        <template v-else>
          <tracking-card
            v-for="(card, index) in signalCards"
            :key="index"
            :stockInfo="stockList[index]"
            :signals="card"
            :sortTimeType="sortTimeType"
          ></tracking-card>
        </template>
        <div class="record-block" v-if="dataList.length">
          <div class="btn" @click.stop="showHolding">
            持仓记录<svg-icon icon="arrow-right"></svg-icon>
          </div>
        </div>
      </div>
    </div>
  </section>
</template>

<script>
import EmptyPool from '@/components/detail/EmptyPool.vue';
import TrackingCard from '@/components/portfolio/TrackingCard.vue';
import EtfList from '@/components/portfolio/EtfList.vue';
import ServicePackStockList from '@/components/servicePack/StockList.vue';
import { ETF_STATUS, BASE_URL } from '@/config/portfolio';
import { reqPortfolioList } from '@/apis/portfolio.api';
import { formatWeek, getWebHQ, timestampToTime } from '@/utils';

const MODE = {
  LIST: 0,
  CARD: 1,
};

const DATE_FORMAT = 'yyyy-MM-dd';

export default {
  components: {
    EmptyPool,
    TrackingCard,
    EtfList,
    ServicePackStockList,
  },
  props: {
    title: {
      type: String,
      default: '',
    },
    emptyText: {
      type: String,
      default: '暂无推荐，请持续关注',
    },
  },
  computed: {
    isNoData() {
      return !this.dataList.length && !this.showLoading;
    },
    signalCards() {
      return this.cardList.map(card => (Array.isArray(card) ? [...card] : []));
    },
  },
  data() {
    return {
      showLoading: false,
      // 列表卡片模式，默认列表
      currentMode: MODE.LIST,
      // 全量数据
      dataList: [],
      // 列表展示数据
      stockList: [],
      // 卡片展示数据
      cardList: [],
      // 按日期分类全量数据
      tableMap: {},
      // 按日期分类卡片数据
      cardMap: {},
      // 是否显示日期控件
      showDatePick: false,
      // 当前选中日期
      selectedDate: new Date(),
      // 最大可选日期
      maxDate: new Date(),
      // 日期弹窗
      showCalendar: false,
      // 有效日期
      validDates: [],
      // 按哪一种时间类型排序
      sortTimeType: 'trade_time',
    };
  },
  created() {
    const portfolioId = window.getParam('portfolio_id');
    if (portfolioId) {
      this.getStrategyPoolData(portfolioId);
    }
  },
  methods: {
    async getStrategyPoolData(portfolio_id) {
      const query = {
        portfolio_id,
        with_records: 1,
        status_list: Object.keys(ETF_STATUS),
      };
      this.showLoading = true;
      try {
        const res = await reqPortfolioList(query);
        if (res.status_code === 0 && res?.data?.length) {
          await this.handleDataList(res.data);
          this.getValidDate();
        }
      } catch (err) {
        const errInfo = {
          name: `getStrategyPoolData方法接口调用错误。${err.name}`,
          message: `接口入参为${JSON.stringify(query)}。${err.message}`,
          stack: err.stack,
          category: 'js',
        };
        _t.errorReport(errInfo);
      } finally {
        this.showLoading = false;
      }
    },
    async handleDataList(list) {
      const group = list.filter(item => !!item['open_date']);
      group.sort((a, b) => (a['open_date'] < b['open_date'] ? 1 : -1));
      const data = group.map(item => {
        item['stock_code'] = item['code'];
        return item;
      });
      this.dataList = await getWebHQ(data);
      for (const item of this.dataList) {
        // 3代表'yyyy-MM-dd'
        const DATE_TYPE = 3;
        const date = timestampToTime(item['open_date'], DATE_TYPE);
        const dateList = this.tableMap[date] || [];
        const records = item.trade_records;
        records.sort((a, b) => (a[this.sortTimeType] < b[this.sortTimeType] ? 1 : -1));
        if (dateList.length) {
          const flag = dateList.find(d => d.id === item.id);
          if (!flag) {
            this.tableMap[date].push(item);
            this.cardMap[date].push(item.trade_records);
          }
        } else {
          this.tableMap[date] = [item];
          this.cardMap[date] = [item.trade_records];
        }
      }
    },
    onDateChange(val) {
      this.selectedDate = val;
    },
    show() {
      this.showCalendar = true;
    },

    confirm(date) {
      this.showCalendar = false;
      this.selectedDate = date;
    },
    filterDate(days) {
      return days.filter(day => this.validDates.includes(window.Acme.formatDate(day, DATE_FORMAT)));
    },
    filterCalendar(date) {
      return this.validDates.includes(window.Acme.formatDate(date, DATE_FORMAT));
    },
    weekFormatter(date) {
      return formatWeek(date);
    },
    getValidDate() {
      try {
        this.validDates = Object.keys(this.tableMap);
        const lastDate = this.validDates[0];
        this.selectedDate = new Date(lastDate);
        const carObj = this.cardMap[lastDate] || [];
        this.cardList = [...carObj];
        this.stockList = this.tableMap[lastDate];
        this.showDatePick = true;
      } catch (err) {
        _t.errorReport({
          name: `portfolio/StrategyPool.vue的getValidDate方法错误。${err.name}`,
          message: err.message,
          stack: err.stack,
          category: 'js',
        });
      }
    },
    showHolding() {
      location.href = `${BASE_URL}position?portfolio_id=${window.getParam('portfolio_id')}&mode=${
        this.currentMode
      }&sortTimeType=${this.sortTimeType}&title=策略池&type=normal`;
    },
  },
  watch: {
    selectedDate(date) {
      try {
        const dateStr = window.Acme.formatDate(date, DATE_FORMAT);
        const carObj = this.cardMap[dateStr] || {};
        const carArr = Object.values(carObj);
        this.cardList = carArr;
        const stockList = this.tableMap[dateStr] || [];
        this.stockList = stockList;
      } catch (err) {
        const errInfo = {
          name: `selectedDate方法异常。${err.name}`,
          message: err.message,
          stack: err.satck,
          category: 'js',
        };
        _t.errorReport(errInfo);
      }
    },
  },
};
</script>

<style lang="less" scoped>
.atom-calendar-tab {
  width: 100%;
}

section {
  background: var(--bg-color-2);
  border-radius: 6px;
  padding: 12px 10px;
  margin-bottom: 8px;
  .title {
    font-size: 18px;
    line-height: 22px;
    font-weight: 600;
    color: var(--text-1);
  }
}

.strategy-pool {
  box-sizing: border-box;
  min-height: 426px;
  height: auto;
  position: relative;
}

.box-center {
  height: 380px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.tool {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  line-height: 18px;
  color: var(--text-1);
  padding: 16px 0;
  .icon-btn {
    display: flex;
    align-items: center;
    svg {
      margin-right: 4px;
    }
  }
  .title {
    display: flex;
    align-items: center;
    font-size: 18px;
    line-height: 22px;
    color: var(--text-1);
  }
  .toggle {
    display: flex;
    align-items: center;
  }
  .btn {
    color: var(--text-2);
    &.active {
      color: var(--text-1);
      font-weight: 600;
    }
  }
  .split {
    width: 1px;
    height: 12px;
    background: var(--text-4);
    margin: 0 12px;
  }
}

/deep/.atom-sticky--fixed .tool {
  padding: 16px;
  background: var(--bg-color-2);
}

.record-block {
  font-size: 14px;
  line-height: 18px;
  color: var(--text-3);
  padding-top: 4px;
  display: flex;
  justify-content: center;
  .btn {
    width: 120px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
